package jianzhiOffer;

/**
 * 写一个函数，求两个整数之和，要求在函数体内不得使用 “+”、“-”、“*”、“/” 四则运算符号。
 */
public class T00065 {
    public static void main(String[] args) {
        int[] arr = new int[]{
                1, 1,
                2, 5,
                11, 4,
                5, 6,
                -3, 5,
                -1, -1,
                0, 0,
                0, 1,
                -3, 0,
                1, 0,
                0, -3,
                Integer.MAX_VALUE, 1,
                1, Integer.MAX_VALUE,
                Integer.MAX_VALUE, Integer.MAX_VALUE
        };
        int[] rs = new int[] {
                2,
                7,
                15,
                11,
                2,
                -2,
                0,
                1,
                -3,
                1,
                -3,
                Integer.MAX_VALUE + 1,
                Integer.MAX_VALUE + 1,
                Integer.MAX_VALUE + Integer.MAX_VALUE
        };
        Solution solution = new Solution();
        for (int i = 0, j = 0; i < arr.length - 1 && j < rs.length; ) {
            if(rs[j] != solution.add(arr[i ++], arr[i])) {
                System.err.printf("%d + %d ! = %d\n", arr[i - 1], arr[i], rs[j]);
                throw new RuntimeException();
            }
            System.out.printf("TEST OK: %d + %d == %d\n", arr[i - 1], arr[i], rs[j]);
            j ++;
            i ++;
        }
        System.out.println("ok");
    }

static class Solution {
    public int add(int a, int b) {
        int xor, and;
        for(;;) {
            xor = a ^ b;
            and = a & b;
            if (and == 0)
                return xor;
            a = xor;
            b = and << 1;
        }
    }
}
}